import mitt from 'mitt'

const socketMitt = mitt()
let webSocket: any = null;
const heartbeatTimeout: number = 5000 //心跳时长
const reConnectTimeout: number = 5000

var baseUrl = import.meta.env.VITE_WS
if (baseUrl === '') {
    baseUrl = 'ws://' + location.host
}
const path = 'ws-script'
const webSocketUrl = `${baseUrl}/${path}`

var isConnect: boolean = false
var rec: any = null
const checkMsg = 'heartbeat'
var timeoutObj: any = null

const createWebSocket = () => {
    webSocket = new WebSocket(webSocketUrl)
    initWebsocket()
}

const initWebsocket = () => {
    webSocket.onopen = webSocketOnOpen;
    webSocket.onmessage = webSocketOnMessage;
    webSocket.onclose = webSocketClose;
}

const webSocketOnOpen = () => {
    isConnect = true
    socketMitt.emit('webSocketOnOpen')
    clearInterval(timeoutObj)
    timeoutObj = setInterval(() => {
        if (isConnect) {
            webSocket.send(checkMsg)
        }
    }, heartbeatTimeout)
}

const webSocketOnMessage = (e: any) => {
    var data = JSON.parse(e.data)
    socketMitt.emit(data.type, data.msg)
}

const webSocketClose = () => {
    isConnect = false
    socketMitt.emit('webSocketClose')
    clearInterval(timeoutObj)
    webSocketReConnect()
}

const webSocketReConnect = () => {
    if (isConnect) {
        return
    }
    clearTimeout(rec)
    rec = setTimeout(() => {
        createWebSocket()
    }, reConnectTimeout)
}

createWebSocket()
export default socketMitt